<?php
class Services
{
	public static function invoke($service, Context $context, $silent = false )
	{
		$context->silent = $silent;
		$instance = self::getInstance($service);

		if ( !$instance ) {
			return(true);
		}

		if ( !Session::$context ) {
			Session::$context = $context;
		}
		else {
			Context::merge(Session::$context, $context);
		}

		if ( $context->endpointName ) {
			// Si se especificó el nombre de un endpoint,
			// lo ejecuta en lugar del entrypoint.
			//

			$endpoint = $context->endpointName;

			if ( method_exists($instance, $endpoint) ) {
				$return = $instance->$endpoint($context);
			}
			else {
				$return = $instance->execute($context);
			}
		}
		else {
			$return = $instance->execute($context);
		}

		ServiceResponse::setValue( "endpointName", $context->endpointName );

		return($instance);
	}

	public static function getInstance($serviceName)
	{
		if( !ClassLoader::getInstance()->loadClass( $serviceName ) ) {
			ServiceResponse::raiseError( ServiceUnavailableException, null, "Services");
		}

		$instance = ClassLoader::getInstance()->uniqueInstance( $serviceName );

		return($instance);
	}
}
?>
